import React, {FC, useEffect} from 'react';
import {View, StyleSheet} from 'react-native';
import HomeStore from '../../stores/HomeStore';
import Item from './components/Item';
import Footer from './components/Footer';
import Header from './components/Header';
import {observer} from 'mobx-react';
import FlowList from '../../components/flowlist/FlowList.js';
import Title from './components/Title';
import {usePushy} from 'react-native-update';
type PropsType = {};
const Home: FC<PropsType> = observer(() => {
  useEffect(() => {
    HomeStore.requestHomeList();
    checkPatch();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const refreshListData = () => {
    HomeStore.resetPage();
    HomeStore.requestHomeList();
  };
  const loadMoreData = () => {
    HomeStore.requestHomeList();
  };
  const {
    checkUpdate,
    updateInfo,
    downloadUpdate,
    switchVersion,
    switchVersionLater,
  } = usePushy();
  const checkPatch = async () => {
    await checkUpdate();
    console.log(
      'name:',
      updateInfo?.name,
      'description:',
      updateInfo?.description,
    );
    const {forceUpdate} = JSON.parse(updateInfo?.metaInfo || '') || {};
    if (updateInfo?.update) {
      await downloadUpdate();
      if (forceUpdate) {
        switchVersion();
      } else {
        switchVersionLater();
      }
    }
  };

  return (
    <View style={styles.root}>
      <Title tab={1} />
      <FlowList
        style={styles.flatList}
        contentContainerStyle={styles.container}
        data={HomeStore.homeList}
        keyExtractor={(item: any) => `${item.id}`}
        renderItem={({item}: {item: any}) => <Item item={item} />}
        numColumns={2}
        refreshing={HomeStore.refreshing}
        onRefresh={refreshListData}
        onEndReachedThreshold={0.1}
        onEndReached={loadMoreData}
        ListFooterComponent={<Footer />}
        ListHeaderComponent={<Header />}
      />
    </View>
  );
});

const styles = StyleSheet.create({
  root: {
    width: '100%',
    height: '100%',
    backgroundColor: '#f0f0f0',
    justifyContent: 'center',
    alignItems: 'center',
  },
  flatList: {
    width: '100%',
    height: '100%',
  },
  container: {
    borderTopColor: '#ddd',
    borderTopWidth: 1,
  },
});
export default Home;
